package Thread;
//模拟实现 阻塞队列
class MyBlockqueue{
    private String[] data=null;
    //队首
    private int head=0;
    //队尾
    private int tail=0;
    //元素个数
    private int size;
    public MyBlockqueue(int capaticy){
      data=new String[capaticy];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while (size>= data.length) {
                //满了 需要阻塞
                this.wait();
            }

            data[tail]=elem;
            tail++;
            if(tail>=data.length){
                tail=0;
            }
            size++;
            this.notify();
        }

    }
    public String take() throws InterruptedException {
        synchronized (this){
            while (size==0){
                //为空 需要阻塞
                this.wait();
            }
            String ret=data[head];
            head++;
            if(head>=data.length){
                head=0;
            }
            size-- ;
            this.notify();
            return ret;
        }
        }
}
public class Dom30 {
    public static void main(String[] args) throws InterruptedException {
         MyBlockqueue myBlockqueue=new MyBlockqueue(1000);
         Thread producer=new Thread(()->{
             int n=0;
             while (true) {
                 try {
                     myBlockqueue.put(n + "");
                     System.out.println("生产元素" + n);
                     n++;
                 } catch (InterruptedException e) {
                     throw new RuntimeException(e);
                 }
             }
         });
        Thread consumer=new Thread(()->{
            while (true) {
                String ret =null;
                try {
                     ret = myBlockqueue.take();
                    System.out.println("消费者元素" + ret);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
          producer.start();
          consumer.start();
    }
}
